import { memo, useContext, useEffect, useRef, useState } from 'react';
import { DataContext } from '../../context/dataContext';

const Son: React.FC = () => {
  const data = useContext(DataContext);

  const list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  const [timer, setTimer] = useState(10);
  const [flag, setFlag] = useState(false);

  const [count, setCount] = useState(1);
  // 初始通过计算拿到
  const [filterList] = useState(() => {
    return list.filter(item => item > 5);
  });

  const changeCount = () => {
    setCount(count => count + 1);
    // 此时 ==> 更新数据还是异步的，所以无法打印出最新值
    console.log('count 1 ===> ', count);
  };

  const changeCount2 = () => {
    setTimeout(() => {
      setCount(count => count + 1);
      console.log('count 2 ===> ', count);
    });
  };

  useEffect(() => {
    document.title = `${count}`;
  }, [count]);

  useEffect(() => {
    setInterval(() => {
      setTimer(timer => timer - 1);
    }, 1000);
  }, []);

  const iptRef = useRef<HTMLInputElement>(null);

  // useRef有缓存的功能  createRef会产生不同的ref对象

  useEffect(() => {
    // 首次聚焦
    iptRef.current?.focus();
  }, [iptRef]);

  const getIptValue = () => {
    console.log(iptRef.current?.value || 'default value');
  };

  return (
    <div className="son">
      <p>拿到dataContext共享数据: {data.join('-')}</p>
      <p>count === {count}</p>
      <button onClick={changeCount}>change count</button>
      <button onClick={changeCount2}>change count2</button>
      <ul>
        {filterList.map(item => {
          return <li key={item}>{item}</li>;
        })}
      </ul>
      <p>倒计时: {timer}</p>
      <div>{flag && <Test />}</div>
      <button onClick={() => setFlag(!flag)}>toggle flag</button>
      <br />
      <input type="text" ref={iptRef} />
      <br />
      <button onClick={getIptValue}>拿到input的值</button>
      <Test2 />
    </div>
  );
};

export default Son;

const Test = memo(() => {
  const [timer, setTimer] = useState(10);

  useEffect(() => {
    console.log('test effect...');

    return () => {
      console.log('test destory...');
    };
  });

  useEffect(() => {
    const timer = setInterval(() => {
      setTimer(timer => timer - 1);
    }, 1000);
    return () => {
      console.log('clear timer...');
      clearInterval(timer);
    };
  });

  return (
    <>
      <div>Test Component...</div>
      <p>test timer: {timer}</p>
    </>
  );
});

const Test2 = () => {
  const [timer, setTimer] = useState(10);

  const temp = useRef<NodeJS.Timer | null>(null);

  // 此处会形成闭包
  const startTimer = () => {
    temp.current && clearInterval(temp.current);
    temp.current = setInterval(() => {
      setTimer(timer => timer - 1);
    }, 1000);
  };

  return (
    <>
      <p>Test2 倒计时: {timer}</p>
      <button onClick={startTimer}>开始倒计时</button>
    </>
  );
};
